//
//  GMVideoExerciseCell.m
//  Teecloud
//
//  Created by xhkj on 2018/11/20.
//  Copyright © 2018 小志. All rights reserved.
//

#import "GMVideoExerciseCell.h"
#import "GMSubjectsModel.h"

#import "GMExeTabHeadCell.h"
#import "GMSubjectsItem.h"

#import "GMExeTabCell.h"
#import "GMNextBtnCell.h"
#import "GMAnserCell.h"
#import "GMExplainCell.h"

@interface GMVideoExerciseCell()<UITableViewDataSource,UITableViewDelegate>
/**用来显示组合题的内容*/
@property (weak, nonatomic) IBOutlet UITextView *textView;
/**组合题内容的高度，如果没有内容，高度等于0，默认250*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textViewHight;
/**中间凸起的图片,当组合题有值，才显示这个图片*/
@property (weak, nonatomic) IBOutlet UIImageView *tuqImg;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tuqHight;
/**用来显示小题的内容*/
@property (weak, nonatomic) IBOutlet UITableView *tabView;
/**习题名字*/
@property (weak, nonatomic) IBOutlet UILabel *titleName;
/**当前习题*/
@property (weak, nonatomic) IBOutlet UILabel *curentCount;
/**总题数*/
@property (weak, nonatomic) IBOutlet UILabel *totalCount;
/**选项卡数组*/
@property (nonatomic, strong) NSMutableArray *tabData;
/**当前时间,  本题开始时间【必须是 yyyy-MM-dd HH:mm:ss 格式】*/
@property (nonatomic, copy) NSString *currentTime;
/**本题答题时长（秒）*/
@property (nonatomic, assign) NSInteger second;
/**创建计时器*/
@property (nonatomic, strong) NSTimer *timer;

@end
@implementation GMVideoExerciseCell

- (void)awakeFromNib {
    [super awakeFromNib];
    /**设置textView不可编辑*/
    [self.textView setEditable:NO];
    self.tabView.dataSource = self;
    self.tabView.delegate = self;
    [self.tabView registerNib:[UINib nibWithNibName:@"GMExeTabHeadCell" bundle:nil] forCellReuseIdentifier:@"GMExeTabHeadCell"];
    [self.tabView registerNib:[UINib nibWithNibName:@"GMExeTabCell" bundle:nil] forCellReuseIdentifier:@"GMExeTabCell"];
    [self.tabView registerNib:[UINib nibWithNibName:@"GMNextBtnCell" bundle:nil] forCellReuseIdentifier:@"GMNextBtnCell"];
    self.currentTime = [NSString getCurrentTimes];
    self.second = 0;
    /**开辟一个子线程调用定时器*/
    kWeakObject(self)
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        weakself.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(Timered:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:weakself.timer forMode:NSRunLoopCommonModes];
        [[NSRunLoop currentRunLoop] run];
    });
}
- (void)Timered:(NSTimer*)timer {
    self.second ++;
    
}
-(NSMutableArray *)tabData{
    if (!_tabData) {
        _tabData = [[NSMutableArray alloc] init];
    }
    return _tabData;
}

-(void)setIndex:(NSInteger)index{
    _index = index;
    self.curentCount.text = [NSString stringWithFormat:@"%ld",index];
}
-(void)setTotal:(NSInteger)total{
    _total = total;
    self.totalCount.text = [NSString stringWithFormat:@"/%ld",total];
}
-(void)setModel:(GMSubjectsModel *)model{
    _model = model;
    if (kIsEmptyString(model.GroupContent)) {
        self.textView.hidden = YES;
        self.textViewHight.constant = 0;
        self.tuqImg.hidden = YES;
        self.tuqHight.constant =0;
    }else{
        self.textView.hidden = NO;
        self.textViewHight.constant = 250;
        self.tuqImg.hidden = NO;
        self.tuqHight.constant =30;
        NSMutableAttributedString *str=  [[NSMutableAttributedString alloc] initWithData:[model.GroupContent dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
        [str addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(0, str.length)];
        self.textView.attributedText = str;
    }
    [self.tabData removeAllObjects];
    [self.tabData addObjectsFromArray:model.Items];
    
    /**在这里操纵数据源，用于控制答案的选中状态*/
    //将字符串整体作为分割条件 返回值为NSArray不可变数组
    //如果答案不为空，说明上一次有答题。要记录答题结果
    NSArray * array = [model.Answer componentsSeparatedByString:@","];
    for (NSInteger i=0; i<array.count; i++) {
        NSString *temStr = array[i];
        for (NSInteger j =0; j<self.tabData.count; j++) {
            if ([temStr isEqualToString:@"A"]) {
                GMSubjectsItem *itemModel = self.tabData[0];
                itemModel.selected = YES;
                itemModel.selctedAnswer = temStr;
            }else if ([temStr isEqualToString:@"B"]){
                GMSubjectsItem *itemModel = self.tabData[1];
                itemModel.selected = YES;
                itemModel.selctedAnswer = temStr;
            }else if ([temStr isEqualToString:@"C"]){
                GMSubjectsItem *itemModel = self.tabData[2];
                itemModel.selected = YES;
                itemModel.selctedAnswer = temStr;
            }else if ([temStr isEqualToString:@"D"]){
                GMSubjectsItem *itemModel = self.tabData[3];
                itemModel.selected = YES;
                itemModel.selctedAnswer = temStr;
            }else if ([temStr isEqualToString:@"E"]){
                GMSubjectsItem *itemModel = self.tabData[4];
                itemModel.selected = YES;
                itemModel.selctedAnswer = temStr;
            }else if ([temStr isEqualToString:@"F"]){
                GMSubjectsItem *itemModel = self.tabData[5];
                itemModel.selected = YES;
                itemModel.selctedAnswer = temStr;
            }else if ([temStr isEqualToString:@"G"]){
                GMSubjectsItem *itemModel = self.tabData[6];
                itemModel.selected = YES;
                itemModel.selctedAnswer = temStr;
            }
        }
    }
    [self.tabView reloadData];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([self.model.TypeCode isEqualToNumber:@(2)]) {
         return self.tabData.count +2;
    }else{
         return self.tabData.count +1;
    }
   
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        GMExeTabHeadCell *headCell = [tableView dequeueReusableCellWithIdentifier:@"GMExeTabHeadCell" forIndexPath:indexPath];
        headCell.model = self.model;
        return headCell;
    }else if(indexPath.row ==self.tabData.count+1){
        GMNextBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GMNextBtnCell" forIndexPath:indexPath];
        [cell.nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];
        if (self.index == self.total) {
            [cell.nextBtn setTitle:@"提交" forState:UIControlStateNormal];
        }else{
            [cell.nextBtn setTitle:@"下一题" forState:UIControlStateNormal];
        }
        return cell;
    }else{
        GMExeTabCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GMExeTabCell" forIndexPath:indexPath];
        GMSubjectsItem *itemModel =self.tabData[indexPath.row-1];
        cell.model = itemModel;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return self.model.titleHight;
    }else if(indexPath.row ==self.tabData.count+1){
        return 44;
    }else{
        GMSubjectsItem *itemModel =self.tabData[indexPath.row-1];
        return itemModel.cellHight;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        
    }else if(indexPath.row ==self.tabData.count+1){
        
    }else if(indexPath.row ==self.tabData.count+2){
        
    }else if(indexPath.row ==self.tabData.count+3){
        
    }else{
        if ([self.model.TypeCode isEqualToNumber:@(2)]) {
            /**多选题*/
            GMSubjectsItem *itemModel =self.tabData[indexPath.row-1];
            if (itemModel.selected) {
                itemModel.selected = NO;
            }else{
                itemModel.selected = YES;
            }
            [self.tabView reloadData];
        }else{
            /**单选或者判断*/
            for (NSInteger i=0; i<self.model.Items.count; i++) {
                GMSubjectsItem *itemModel =self.model.Items[i];
                itemModel.selected = NO;
            }
            GMSubjectsItem *itemModel =self.tabData[indexPath.row-1];
            if (itemModel.selected) {
                itemModel.selected = NO;
            }else{
                itemModel.selected = YES;
            }
            [self.tabView reloadData];
            [self nextBtnClick];
        }
    }
}
-(void)nextBtnClick{
    /**提交的时候把定时器停止*/
    [self.timer invalidate];
    self.model.StartTime = self.currentTime;
    self.model.UseTime = [NSString stringWithFormat:@"%ld",self.second];
    /**选项答案*/
    NSMutableString *answer =[NSMutableString string];
    for (NSInteger i=0; i<self.model.Items.count; i++) {
        GMSubjectsItem *itemModel =self.model.Items[i];
        if (itemModel.selected) {
            switch (itemModel.SortNo) {
                case 0:{
                    [answer appendString:@"A,"];
                }
                    break;
                case 1:{
                    [answer appendString:@"B,"];
                }
                    break;
                case 2:{
                    [answer appendString:@"C,"];
                }
                    break;
                case 3:{
                    [answer appendString:@"D,"];
                }
                    break;
                case 4:{
                    [answer appendString:@"E,"];
                }
                    break;
                case 5:{
                    [answer appendString:@"F,"];
                }
                    break;
                case 6:{
                    [answer appendString:@"G,"];
                }
                    break;
                    
                default:
                    break;
            }
        }
    }
    if (kIsEmptyString(answer)) {
        /**如果没有选中答案点击下一题，直接进入下一题*/
        if (self.index == self.total) {
            /**提交所有答案*/
            self.sumbitBlock();
        }else{
            //下一题
            self.nextBlock();
        }
    }else{
        /**选中了答案，就保存答案，在进入下一题*/
        /**有答案了在去除最后的逗号*/
        NSRange deleteRange = {[answer length] - 1, 1 };
        [answer deleteCharactersInRange:deleteRange];
        self.model.Answer = answer;
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"examId":self.model.examId,
                              @"subjectId":self.model.Id,
                              @"answer":self.model.Answer,
                              @"startTime":self.model.StartTime,
                              @"timeLen":self.model.UseTime
                              };
        [MBProgressHUD showHUDAddedTo:kGHAlertViewKeyWindow animated:YES];
        [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostExamDataCache&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
            [MBProgressHUD hideHUDForView:kGHAlertViewKeyWindow animated:YES];
            if (!error) {
                if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                    /**如果没有选中答案点击下一题，直接进入下一题*/
                    if (self.index == self.total) {
                        /**提交所有答案*/
                        self.sumbitBlock();
                    }else{
                        //下一题
                        self.nextBlock();
                    }
                }
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:kGHAlertViewKeyWindow];
            }
        }];
    }
    
}
-(void)lastBtnClick{
    self.lastBlock();
}
@end
